package com.edee.bigday.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.edee.bigday.search.config.BigdayElasticSearchConfig;
import com.edee.bigday.search.constant.EsConstant;
import com.edee.bigday.search.service.CommoditySaveService;
import com.edee.common.to.es.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommoditySaveServiceImpl implements CommoditySaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public boolean commodityStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //保存到ES中：
        //1、在ES中创建索引“commodity”，并建立映射关系：

        //2、在ES中保存数据：
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //1)构造保存请求：
            IndexRequest indexRequest = new IndexRequest(EsConstant.COMMODITY_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, BigdayElasticSearchConfig.COMMON_OPTIONS);
        //TODO 1、如果批量保存错误，需要处理错误：
        boolean b = bulkResponse.hasFailures();
        List<String> collect = Arrays.stream(bulkResponse.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
//        log.error("商品上架异常：{}",collect);
        log.info("商品上架完成：{}，返回数据：{}",collect,bulkResponse.toString());
        return b;
    }
}
